package cn.middle.edge.config;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.middle.common.result.ApiResponse;

import cn.dev33.satoken.exception.NotLoginException;

/**
 * 全局异常捕获
 * 
 * @author KING
 *
 */
@ControllerAdvice
public class CaptureExceptionHandler {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@SuppressWarnings("rawtypes")
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public ApiResponse handleException(HttpServletRequest reqeust, Exception e) {
		logger.error(e.getMessage(), e);
//		if(e instanceof NotLoginException) { //未登陆
//			return ApiResponse.FAIL_WITH_NOT_LOGIN_ERROR;
//		}else 
		if (e instanceof BindException) { // 自定义参数校验失败异常
			BindException ex = (BindException) e;
			List<ObjectError> errors = ex.getAllErrors();
			if (!errors.isEmpty()) {
				StringBuilder builder = new StringBuilder();
				for (ObjectError error : errors) {
					builder.append(error.getDefaultMessage()).append(",");
				}
				if (builder.length() > 1) {
					return ApiResponse.FailCustomWithMessage(String.valueOf(-1000),
							builder.substring(0, builder.length() - 1));
				}
			}
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), e.getMessage());
		}
		return ApiResponse.UNKNOWN_ERROR;
	}

	/**
	 * 跳转到登陆界面
	 * @param request
	 * @param response
	 */
	@ExceptionHandler(value = NotLoginException.class)
	public void LoginRedirect(HttpServletRequest request,HttpServletResponse response) {
		try {
			response.sendRedirect("/login");
		} catch (IOException e) { 
			logger.error(e.getMessage(), e);
		}
	}

}
